package cn.hallele.bbts.core.component.aspect;

import cn.hallele.bbts.core.common.constants.ArrayConst;
import cn.hallele.bbts.core.common.constants.MsgCodeConst;
import cn.hallele.bbts.core.common.utils.HttpUtil;
import cn.hallele.bbts.core.component.io.BBTSHeader;
import cn.hallele.bbts.core.component.io.BBTSResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

/**
 * ControllerAspect
 *
 * @author anle5
 * @since 2023/12/10 星期日 18:26
 */
@Slf4j
@Aspect
@Component
public class ControllerAspect {
    @Autowired
    private MessageSource i18n;

    /**
     * cut
     */
    @Pointcut(value = "execution(public * cn.hallele.bbts..*Controller.*(..))")
    public void cut() {
    }

    /**
     * 拦截所有cn.hallele.bbts下的controller
     *
     * @param joinPoint joinPoint
     * @return Object
     */
    @Around("cut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            BBTSResponse<?> response = (BBTSResponse<?>) joinPoint.proceed();
            BBTSHeader header = response.getHeader();
            header.setIpIfBlank(HttpUtil.getClientIp());
            header.setAccessDeviceIfBlank(HttpUtil.getClientPlatformName());
            header.setMsgDesc(i18n.getMessage(header.getMsgCode(), ArrayConst.EMPTY_OBJECT, MsgCodeConst.SUCCESS, HttpUtil.getLocale()));
            return response;
        } catch (Throwable e) {
            log.error("Response assembly failed", e);
            throw e;
        }
    }
}
